package cn.lin.service.impl;

import cn.lin.config.RabbitMQConfig;
import cn.lin.handler.SignInWebSocketHandler;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;
import com.rabbitmq.client.Channel;

import java.io.IOException;

/**
 * MQ 消息监听方法
 * 
 * @author cn.Lin
 * @create 2024-12-04-11:52
 */
@Service
public class MessageReceiver {

    @Autowired
    private SignInWebSocketHandler signInWebSocketHandler;

    @RabbitListener(queues = RabbitMQConfig.SIGN_IN_QUEUE)
    public void receiveSignInMessage(@Payload Integer stuId, Message message, Channel channel) {
        // 获取消息的deliveryTag
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            // 收到消息后，通过WebSocket通知对应的学生
            signInWebSocketHandler.notifyStudent(stuId);

            // 确认消息已处理
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                Boolean redelivered = message.getMessageProperties().getRedelivered();
                if (redelivered) {
                    // 消息已重试过,直接丢弃
                    channel.basicNack(deliveryTag, false, false);
                } else {
                    // 重新入队列重试
                    channel.basicNack(deliveryTag, false, true);
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
